package db;

import interfaces.IFOrder;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import model.Customer;
import model.Invoice;
import model.Order;
import model.ProductLine;

public class OrderDb implements IFOrder {
	protected Connection con;

	public void connectDb() {
		con = DbConnection.getInstance().getDBcon();
	}

	public void disconnectDb() {
		DbConnection.getInstance();
		DbConnection.closeConnection();
	}

	public OrderDb() {
		connectDb();
	}

	@Override
	public void insertOrder(Order order, Customer customer, Invoice invoice) throws Exception {
		String query = 
				"INSERT INTO Order (customerId, invoiceId) " +
				"VALUES ('" + customer.getCustomerId() + "','" + invoice.getInvoiceId() + "');" +
				"INSERT INTO Invoice (invoiceId, amount)" +
				"VALUES ('" + invoice.getInvoiceId() +"','" +invoice.getAmount() + "');";
				for(ProductLine pl : order.getProducts())
				{
					order.insertProduct(pl);
				}
		System.out.println("QUERRY : " + query);
		try {
			System.out.println("Inserting order ...");
			Statement stmt = con.createStatement();
			stmt.setQueryTimeout(5);
			stmt.executeUpdate(query);
			stmt.close();
			System.out.println("SUCCESS: Querry executed!");
		}// end try
		catch (SQLException ex) {
			System.out.println("ERROR:" + ex.getMessage());
		}
	}

	@Override
	public void insertProduct(int orderId, ProductLine productLine) throws Exception {
		String query = 
				"INSERT INTO OrderProducts (orderId, productId, quantity) " +
				"VALUES ('" + orderId + "','" + productLine.getProduct().getProductId() + "','" + productLine.getQuantity() + "')";
		System.out.println("QUERRY : " + query);
		try {
			System.out.println("inserting in order ...");
			Statement stmt = con.createStatement();
			stmt.setQueryTimeout(5);
			stmt.executeUpdate(query);
			stmt.close();
			System.out.println("SUCCESS: Querry executed!");
		}// end try
		catch (SQLException ex) {
			System.out.println("ERROR:" + ex.getMessage());
		}
		
	}

	@Override
	public int searchOrder(int customerId, int invoiceId) throws Exception {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void calculatePrice(Order order) throws Exception {
		String query = 
				"INSERT INTO Invoice (price) " +
				"VALUES ('" + order.getPrice() + "')";
		System.out.println("QUERRY : " + query);
		try {
			System.out.println("inserting in order ...");
			Statement stmt = con.createStatement();
			stmt.setQueryTimeout(5);
			stmt.executeUpdate(query);
			stmt.close();
			System.out.println("SUCCESS: Querry executed!");
		}// end try
		catch (SQLException ex) {
			System.out.println("ERROR:" + ex.getMessage());
		}
	}

}
